package flib;

import java.util.Collections;
import java.util.Vector;

import simpleGeom.HasLine2D;
import simpleGeom.HasPos2D;
import simpleGeom.Vec2D;

public class Splitter {
	Vector<? extends HasPos2D> outline;
	Vector<? extends HasLine2D> segments;

	public SplitEvent split(HasPos2D pos, Vec2D dir,
			Vector<? extends FlibHEdge> segments, float tol) {
		Vector<SplitEvent> splitevents = new Vector<SplitEvent>();
		for (int i = 0; i < segments.size(); i++) {
			FlibHEdge l = segments.get(i);
			if (Vec2D.dist(l.getOrg(), pos) > tol
					&& Vec2D.dist(l.getDest(), pos) > tol) {
				Vec2D v = l.rayIntersection(pos.getX(), pos.getY(), dir.getX(),
						dir.getY(), 0.01f);
				if (v != null) {
					float d = Vec2D.dist(pos, v);
					SplitEvent sE = new SplitEvent(l, v, d);
					splitevents.add(sE);
				}
			}
		}
		if (splitevents.size() > 0) {
			Collections.sort(splitevents);
			return splitevents.firstElement();
		}
		return null;
	}

	class SplitEvent implements Comparable {
		FlibHEdge l;
		HasPos2D s;
		float d;

		public SplitEvent(FlibHEdge hEdge, HasPos2D s, float d) {
			this.l = hEdge;
			this.s = s;
			this.d = d;
		}

		public int compareTo(Object arg0) {
			// TODO Auto-generated method stub
			SplitEvent s2 = (SplitEvent) arg0;
			return Float.compare(d, s2.d);
		}
	}
}
